package com.dify.knowledge.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dify.knowledge.entity.Document;
import com.dify.knowledge.entity.DocumentVersion;
import com.dify.knowledge.service.DocumentService;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 文档管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/documents")
@Validated
public class DocumentController {

    private final DocumentService documentService;

    public DocumentController(DocumentService documentService) {
        this.documentService = documentService;
    }

    /**
     * 上传文档
     * 
     * @param file 上传的文件
     * @param userId 用户ID
     * @return 上传结果
     */
    @PostMapping("/upload")
    public ResponseEntity<DocumentUploadResponse> uploadDocument(
            @RequestParam("file") MultipartFile file,
            @RequestParam("userId") Long userId) {
        
        log.info("收到文档上传请求，文件名：{}，用户ID：{}", file.getOriginalFilename(), userId);
        
        DocumentService.DocumentUploadResult result = documentService.uploadDocument(file, userId);
        
        DocumentUploadResponse response = new DocumentUploadResponse();
        response.setDocumentId(result.getDocumentId());
        response.setFileName(result.getFileName());
        response.setStatus(result.getStatus());
        response.setMessage(result.getMessage());
        
        return ResponseEntity.ok(response);
    }

    /**
     * 获取文档列表
     * 
     * @param page 页码（从1开始）
     * @param size 每页大小
     * @return 分页的文档列表
     */
    @GetMapping("/list")
    public ResponseEntity<Page<Document>> getDocuments(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        log.info("获取文档列表，页码：{}，每页大小：{}", page, size);
        
        Page<Document> documents = documentService.getDocuments(page, size);
        
        return ResponseEntity.ok(documents);
    }

    /**
     * 删除文档
     * 
     * @param documentId 文档ID
     * @return 删除结果
     */
    @DeleteMapping("/{documentId}")
    public ResponseEntity<DeleteDocumentResponse> deleteDocument(
            @PathVariable Long documentId) {
        
        log.info("收到删除文档请求，文档ID：{}", documentId);
        
        documentService.deleteDocument(documentId);
        
        DeleteDocumentResponse response = new DeleteDocumentResponse();
        response.setSuccess(true);
        response.setMessage("文档删除成功");
        
        return ResponseEntity.ok(response);
    }

    /**
     * 获取文档版本列表
     * 
     * @param documentId 文档ID
     * @return 版本列表
     */
    @GetMapping("/{documentId}/versions")
    public ResponseEntity<List<DocumentVersion>> getVersions(
            @PathVariable Long documentId) {
        
        log.info("获取文档版本列表，文档ID：{}", documentId);
        
        List<DocumentVersion> versions = documentService.getVersions(documentId);
        
        return ResponseEntity.ok(versions);
    }

    /**
     * 对比两个版本
     * 
     * @param version1Id 版本1 ID
     * @param version2Id 版本2 ID
     * @return 版本对比结果
     */
    @GetMapping("/compare")
    public ResponseEntity<VersionComparisonResponse> compareVersions(
            @RequestParam Long version1Id,
            @RequestParam Long version2Id) {
        
        log.info("对比文档版本，版本1 ID：{}，版本2 ID：{}", version1Id, version2Id);
        
        DocumentService.VersionComparison comparison = 
                documentService.compareVersions(version1Id, version2Id);
        
        VersionComparisonResponse response = new VersionComparisonResponse();
        response.setVersion1(comparison.getVersion1());
        response.setVersion2(comparison.getVersion2());
        response.setDifferences(comparison.getDifferences());
        
        return ResponseEntity.ok(response);
    }

    /**
     * 启用指定版本
     * 
     * @param versionId 版本ID
     * @return 启用结果
     */
    @PostMapping("/versions/{versionId}/activate")
    public ResponseEntity<VersionActivationResponse> activateVersion(
            @PathVariable Long versionId) {
        
        log.info("收到版本启用请求，版本ID：{}", versionId);
        
        DocumentService.VersionActivationResult result = documentService.activateVersion(versionId);
        
        VersionActivationResponse response = new VersionActivationResponse();
        response.setSuccess(result.getSuccess());
        response.setMessage(result.getMessage());
        response.setVersionNumber(result.getVersionNumber());
        response.setPreviousActiveVersion(result.getPreviousActiveVersion());
        
        return ResponseEntity.ok(response);
    }

    /**
     * 获取文档的当前启用版本
     * 
     * @param documentId 文档ID
     * @return 启用版本
     */
    @GetMapping("/{documentId}/active-version")
    public ResponseEntity<DocumentVersion> getActiveVersion(
            @PathVariable Long documentId) {
        
        log.info("获取文档启用版本，文档ID：{}", documentId);
        
        DocumentVersion activeVersion = documentService.getActiveVersion(documentId);
        
        return ResponseEntity.ok(activeVersion);
    }

    /**
     * 文档上传响应DTO
     */
    @Data
    public static class DocumentUploadResponse {
        /**
         * 文档ID
         */
        private Long documentId;
        
        /**
         * 文件名
         */
        private String fileName;
        
        /**
         * 状态：PROCESSING-处理中, COMPLETED-已完成, FAILED-失败
         */
        private String status;
        
        /**
         * 消息
         */
        private String message;
    }

    /**
     * 删除文档响应DTO
     */
    @Data
    public static class DeleteDocumentResponse {
        /**
         * 是否成功
         */
        private Boolean success;
        
        /**
         * 消息
         */
        private String message;
    }

    /**
     * 版本对比响应DTO
     */
    @Data
    public static class VersionComparisonResponse {
        /**
         * 版本1
         */
        private DocumentVersion version1;
        
        /**
         * 版本2
         */
        private DocumentVersion version2;
        
        /**
         * 差异列表
         */
        private List<String> differences;
    }

    /**
     * 版本启用响应DTO
     */
    @Data
    public static class VersionActivationResponse {
        /**
         * 是否成功
         */
        private Boolean success;
        
        /**
         * 消息
         */
        private String message;
        
        /**
         * 启用的版本号
         */
        private Integer versionNumber;
        
        /**
         * 之前启用的版本号
         */
        private Integer previousActiveVersion;
    }
}
